package cn.zmall.sso.service.impl;

import cn.zmall.common.exception.ZmallException;
import cn.zmall.manager.mapper.TbAddressMapper;
import cn.zmall.manager.pojo.TbAddress;
import cn.zmall.manager.pojo.TbAddressExample;
import cn.zmall.sso.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author cxy
 * @Date 2020/11/12 17:22
 * @Version 1.0
 */
public class AddressServiceImpl implements AddressService {

    @Autowired
    TbAddressMapper tbAddressMapper;

    //获取一个地址
    @Override
    public TbAddress getAddress(Long addressId) {
        TbAddress tbAddress = tbAddressMapper.selectByPrimaryKey(addressId);
        if (tbAddress == null) {
            return null;
        }
        return tbAddress;
    }

    //获取用户地址列表
    @Override
    public List<TbAddress> getListAddress(Long userId) {
        List<TbAddress> tbAddresses = new ArrayList<>();
        TbAddressExample tbAddressExample = new TbAddressExample();
        TbAddressExample.Criteria criteria = tbAddressExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        tbAddresses = tbAddressMapper.selectByExample(tbAddressExample);
        if (tbAddresses == null) {
            return null;
        }
        for (int i = 0; i < tbAddresses.size(); i++) {
            if (tbAddresses.get(i).getIsDefault()) {
                Collections.swap(tbAddresses, 0, i);
                break;
            }
        }
        return tbAddresses;
    }

    @Override
    public int addAddress(TbAddress tbAddress) {
        if (tbAddressMapper.insert(tbAddress) != 1) {
            return -1;
        }
        return 1;
    }

    @Override
    public int delAddress(Long addressId) {
        if (tbAddressMapper.deleteByPrimaryKey(addressId) != 1) {
            return -1;
        }
        return 1;
    }

    @Override
    public int updateAddress(TbAddress tbAddress) {
        if (tbAddressMapper.updateByPrimaryKey(tbAddress) != 1) {
            return -1;
        }
        return 1;
    }


}